package com.bainuo.doctor.common.image_support.imghandle.crop;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.bainuo.doctor.common.base.BaseApplication;
import com.bainuo.doctor.common.image_support.imghandle.Bean.ImageUploadInfo;
import com.bainuo.doctor.common.image_support.imghandle.luban.Luban;
import com.bainuo.doctor.common.image_support.imghandle.luban.OnCompressListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by faraway on 15/2/17.
 */
public abstract class BaseCrop implements IImageCrop {

//    static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();


    static class BaseCropEvent{}

    /**
     * 系统裁剪跳转码
     */
    protected int code;

    /**
     * 跳转activity
     */
    protected Activity activity;

    /**
     * 图片裁剪监听
     */
    protected IImageCrop.Listener listener;

    static private boolean isCompressing;

    static Queue<ImageUploadInfo> imageQueue = new LinkedBlockingQueue<>();

    public BaseCrop(){
//        EventBus.getDefault().register(this);
    }

    @Override
    public void setCode(Activity activity, int code) {
        this.code = code;
        this.activity = activity;
    }


    @Override
    public void setCropListener(IImageCrop.Listener listener) {
        this.listener = listener;
    }

    /**
     * 根据uri获取 path
     *
     * @param uri
     * @return
     */
    @Override
    public String getBitmapPath(Uri uri) {

        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = activity.getContentResolver().query(uri, proj, null, null, null);
        if (cursor.moveToFirst()) {
            ;
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }

//    @Override
//    public Bitmap getBitmap(Uri uri) {
//        return null;
//    }


    @Override
    public void cropImage(final ImageUploadInfo info) {


        //如果正在压缩 则入队
        if (isCompressing) {
            imageQueue.add(info);
            return;
        }

//        if (!lock.writeLock().tryLock()) {
//            imageQueue.add(info);
//            return;
//        }

        if (info.getState() == ImageUploadInfo.STATE_CANCEL){
            onCompressEnd(info);
            return;
        }


        isCompressing = true;
//        lock.lock();
        Luban.get(BaseApplication.getInstance())
                .load(new File(info.getSrcPath()))                     //传人要压缩的图片
                .putGear(Luban.THIRD_GEAR)      //设定压缩档次，默认三挡
                .setCompressListener(new OnCompressListener() { //设置回调

                    @Override
                    public void onStart() {
                        //TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }
                    @Override
                    public void onSuccess(File file) {
                        //TODO 压缩成功后调用，返回压缩后的图片文件
                        info.setUploadPath(file.getPath());
                        onCompressEnd(info);
                    }

                    @Override
                    public void onError(Throwable e) {
                        //TODO 当压缩过去出现问题时调用
                        info.setUploadPath(info.getSrcPath());
                        onCompressEnd(info);
                    }
                }).launch();    //启动压缩
    }

    public void onCompressEnd(ImageUploadInfo info){

        isCompressing = false;
//        lock.writeLock().unlock();

        if(listener != null)
            listener.onCropend(info);


        if (imageQueue.size()>0)
            cropImage(imageQueue.poll());
//        else
//            EventBus.getDefault().post(new BaseCropEvent());

    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void refresh(BaseCropEvent event) {
//        if (imageQueue.size()>0)
//            cropImage(imageQueue.poll());
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void ungisterEventBus(BaseCropEvent event) {
////        EventBus.getDefault().post(new BaseCropEvent());
//    }




//    public void compressImage(Bitmap bitmap) {
////        info.uploadPath = info.getSrcPath();
////        listener.onCropend(info);
////        Luban.
//
//    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

//    @Override
//    protected void finalize() throws Throwable {
//        super.finalize();
//        EventBus.getDefault().unregister(this);
//    }
}
